package com.bootdo.common.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AliyunOSSUtil {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);

    private static final String endpoint=OssConstant.OSS_END_POINT;
    private static final String endpoint2=OssConstant.OSS_END_POINT2;
    private static final String accessKeyId=OssConstant.OSS_ACCESS_KEY_ID;
    private static final String accessKeySecret=OssConstant.OSS_ACCESS_KEY_SECRET;
    private static final String bucketName=OssConstant.OSS_BUCKET_NAME;
    private static final String fileHost=OssConstant.OSS_FILE_HOST;
    private static final String fileHost2=OssConstant.OSS_FILE_HOST2;
    private static final String fileHost3=OssConstant.OSS_FILE_HOST3;
    private static final String endpointHistory_today=OssConstant.OSS_ENDPOINT_HISTORY_TODAY;
    private static final String fileHostHistory_today=OssConstant.OSS_FILE_HOST_HISTORY_TODAY;
    private static final String bucketNameHistory_today=OssConstant.OSS_BUCKETNAME_HISTORY_TODAY;
    public static String uploadFile(File file){
        logger.info("=========>OSS文件上传开始："+file.getName());

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        if(null == file){
            return null;
        }

        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //容器不存在，就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String uuid = String.valueOf(UUID.random(0, 10)+System.currentTimeMillis());
            String fileUrl = fileHost+"/"+(dateStr + "/" + uuid+"-"+file.getName());
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是私有权限读写
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            if(null != result){
                logger.info("==========>OSS文件上传成功,OSS地址："+fileUrl);
                return file.getName()+"#"+fileUrl;
            }

        }catch (OSSException oe){
            logger.error(oe.getMessage());
        }catch (ClientException ce){
            logger.error(ce.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }

    public static boolean uploadConfigFile(File file){
        logger.info("=========>OSS文件上传开始："+file.getName());

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        if(null == file){
            return false;
        }

        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //容器不存在，就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String fileUrl = fileHost2+"/"+file.getName();
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是私有权限读写
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            if(null != result){
                logger.info("==========>OSS文件上传成功,OSS地址："+fileUrl);
                return true;
            }

        }catch (OSSException oe){
            logger.error(oe.getMessage());
        }catch (ClientException ce){
            logger.error(ce.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return false;
    }

    public static void downFile(HttpServletRequest request, HttpServletResponse response, String fileUrl){
        response.reset();// 清空输出流
        OutputStream out = null;

        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1,
                fileUrl.length());

        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {

            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            String filedisplay = System.currentTimeMillis() +"-"+ fileName;
            response.addHeader("Content-Disposition", "attachment;filename="
                    + filedisplay);
            if (request.getHeader("USER-AGENT").toLowerCase()
                    .indexOf("firefox") > 0 ? false : true) {
                filedisplay = "attachment;filename="
                        + URLEncoder.encode(filedisplay, "UTF-8");
            } else {
                filedisplay = "attachment;filename="
                        + new String(filedisplay.getBytes(), "ISO-8859-1");
            }
            response.setContentType("application/x-msdownload;charset=UTF-8");
            response.setHeader("Content-Disposition", filedisplay);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");

            // 设置URL过期时间为1小时
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
            GeneratePresignedUrlRequest generatePresignedUrlRequest ;
            generatePresignedUrlRequest =new GeneratePresignedUrlRequest(bucketName, fileUrl);
            generatePresignedUrlRequest.setExpiration(expiration);
            URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);


            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();// 通过输入流获取数据
            out = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            inStream.close();
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    //获取url地址
    public static String getPackUrl(String value,String type){
        //获取地址
        if("file".equals(type)){
            return "http://"+endpoint+"/"+value;
        }else{
            return "http://"+endpoint2+"/"+value;
        }
    }

    //创建文本文件
    public static String createFile(String name,String value){

        PrintWriter pfp = null;
        String res = "";
        try {
            File fp=new File(OssConstant.OSS_FILE_FILEDIR+File.separator+name+".txt");

            if (!fp.getParentFile().exists()) {
                boolean result = fp.getParentFile().mkdirs();
                if (!result) {
                    System.out.println("创建文件目录失败");
                }
                else fp.createNewFile();
            }
            pfp= new PrintWriter(fp);
            pfp.print(value);
            res = fp.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != pfp){
                pfp.close();
            }
        }
        return res;
    }

    //上传图片
    public static String uploadPicture(File file){
        logger.info("=========>OSS文件上传开始："+file.getName());

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        if(null == file){
            return null;
        }

        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //容器不存在，就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String uuid = String.valueOf(UUID.random(0, 10)+System.currentTimeMillis());
            String fileUrl = fileHost3+"/"+(dateStr + "/" + uuid+"-"+file.getName());
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是私有权限读写
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            if(null != result){
                logger.info("==========>OSS文件上传成功,OSS地址："+fileUrl);
                return file.getName()+"#"+fileUrl;
            }

        }catch (OSSException oe){
            logger.error(oe.getMessage());
        }catch (ClientException ce){
            logger.error(ce.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }

    //根据流上传文件
    public static String uploadInputStream(InputStream is,String endpoint, String fileName){
        logger.info("=========>OSS文件上传开始："+fileName);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());
        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //容器不存在，就创建
            if(! ossClient.doesBucketExist(bucketNameHistory_today)){
                ossClient.createBucket(bucketNameHistory_today);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketNameHistory_today);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String uuid = String.valueOf(UUID.random(0, 10)+System.currentTimeMillis());
            String fileUrl = fileHostHistory_today+"/"+(dateStr + "/" + uuid+"-"+fileName);
            //上传文件
            PutObjectResult result = ossClient.putObject(bucketNameHistory_today,fileUrl,is);
            //设置权限 这里是私有权限读写
            ossClient.setBucketAcl(bucketNameHistory_today,CannedAccessControlList.PublicRead);
            if(null != result){
                logger.info("==========>OSS文件上传成功,OSS地址："+fileUrl);
                return fileUrl;
            }

        }catch (OSSException oe){
            logger.error(oe.getMessage());
        }catch (ClientException ce){
            logger.error(ce.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }
    //根据bucketName fileHost上传文件
    public static String uploadFile(File file, String endpoint, String bucketName, String fileHost){
        logger.info("=========>OSS文件上传开始："+file.getName());
        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //容器不存在，就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
//            String fileUrl = fileHost+"/"+file.getName();
            //创建文件路径
            String uuid = String.valueOf(UUID.random(0, 10)+System.currentTimeMillis());
            String fileUrl = fileHost+"/"+(DateUtil.getCurrentDate()+ "/" + uuid+"-"+file.getName());
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是私有权限读写
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            if(null != result){
                logger.info("==========>OSS文件上传成功,OSS地址："+fileUrl);
                return fileUrl;
            }
        }catch (OSSException oe){
            logger.error(oe.getMessage());
        }catch (ClientException ce){
            logger.error(ce.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }

     /** Txt文件生成方法
      * filedir 文件存放地址
      * name 文件名称
      * value 内容
     * */
    public static String createTxt(String filedir,String name,String value){

        PrintWriter pfp = null;
        String res = "";
        try {
            File fp=new File(filedir+File.separator+name+".txt");

            if (!fp.getParentFile().exists()) {
                boolean result = fp.getParentFile().mkdirs();
                if (!result) {
                    System.out.println("创建文件目录失败");
                }
                else fp.createNewFile();
            }
            pfp= new PrintWriter(fp);
            pfp.print(value);
            res = fp.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != pfp){
                pfp.close();
            }
        }
        return res;
    }

    //根据bucketName fileHost上传文件
    public static String uploadText(File file, String endpoint, String bucketName, String fileHost){
        logger.info("=========>OSS文件上传开始："+file.getName());
        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //容器不存在，就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            String fileUrl = fileHost+"/"+file.getName();
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是私有权限读写
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            if(null != result){
                logger.info("==========>OSS文件上传成功,OSS地址："+fileUrl);
                return fileUrl;
            }
        }catch (OSSException oe){
            logger.error(oe.getMessage());
        }catch (ClientException ce){
            logger.error(ce.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }
}
